//
//  MasterViewController.m
//  rss_reader
//  
//  http://code.google.com/p/epam2012-ios-rss-reader/source/checkout
//  svn checkout https://epam2012-ios-rss-reader.googlecode.com/svn/trunk/ epam2012-ios-rss-reader --username bombrucha@gmail.com

//  machine code.google.com login bombrucha@gmail.com password CY7jN3df2ZV5
//  Created by Oleg Soldatoff on 4/10/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MasterViewController.h"
#import "DetailViewController.h"
#import <QuartzCore/QuartzCore.h>




@implementation MasterViewController

@synthesize newsArray = _newsArray;
@synthesize feedID = _feedID;
@synthesize base = _base;
@synthesize indexPathOfCellSelcted = _indexPathOfCellSelcted;
@synthesize segmentControl = _segmentControl;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
      
      self.tableView.rowHeight = 75;
      self.title = NSLocalizedString(@"News", @"News");
      self.base = [[[DataBase alloc]init]autorelease];
    }
    return self;
}
							
- (void)dealloc
{
  [_indexPathOfCellSelcted release];
  [_base release];
  [super dealloc];
}

- (void)viewDidLoad
{

  [super viewDidLoad];
  UIBarButtonItem *refreshButton = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(refreshRSS:)] autorelease];
  self.navigationItem.rightBarButtonItem = refreshButton;
  
  NSArray *itemArray = [NSArray arrayWithObjects: @"All", @"New", @"To read", nil];
  self.segmentControl = [[[UISegmentedControl alloc] initWithItems:itemArray]autorelease];
  self.segmentControl.frame = CGRectMake(0, 0, 200, 30);
  self.segmentControl.segmentedControlStyle = UISegmentedControlStylePlain;
  self.segmentControl.selectedSegmentIndex = 1;
  self.segmentControl.segmentedControlStyle =   UISegmentedControlStyleBar;
  [self.segmentControl addTarget:self action:@selector(switchNewsView:) forControlEvents:UIControlEventValueChanged];

  UIBarButtonItem *segmentedControlButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:(UIView *)  self.segmentControl]autorelease];
  UIBarButtonItem *flexibleSpace = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]autorelease];
  NSArray *barArray = [NSArray arrayWithObjects: flexibleSpace, segmentedControlButtonItem, flexibleSpace, nil];
  [self setToolbarItems:barArray];
  
  }

- (void)viewDidUnload {
  
  self.newsArray = nil;
  self.base = nil;
  self.indexPathOfCellSelcted = nil;
  [super viewDidUnload];

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void) viewWillAppear:(BOOL)animated {
  
  
  [[NSNotificationCenter defaultCenter] addObserver:self 
                                           selector:@selector(pocessNotification:)  
                                               name:@"BaseUpdated" 
                                             object:nil]; 
  
  [self.navigationController setToolbarHidden:NO];
  self.newsArray =  nil;
  [self.tableView reloadData];
  [super viewWillAppear:animated];
 
}

- (void) viewWillDisappear:(BOOL)animated {
  
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
    [super viewWillDisappear:animated];

}

-(void) viewDidDisappear:(BOOL)animated {

  [self.navigationController setToolbarHidden:YES];
  [super viewDidDisappear:animated];

}

#pragma mark - Table View

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

  return 1;
  
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  
  if ( [self.newsArray count] == 0 ) {
    self.newsArray = [self.base baseNews: self.segmentControl.selectedSegmentIndex 
                               forFeedID: self.feedID]; 
  }
  
  return [self.newsArray count];

}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.font = [UIFont boldSystemFontOfSize:12];
        cell.textLabel.numberOfLines = 4;
        cell.indentationLevel = 0;
      
        cell.detailTextLabel.font = [UIFont boldSystemFontOfSize:10];
      
      
        UILabel *dateRecieveLabel = [[[UILabel alloc]initWithFrame:CGRectMake(240, 3, 70, 12)]autorelease];
        dateRecieveLabel.font = [UIFont systemFontOfSize:10];
        dateRecieveLabel.textAlignment = UITextAlignmentCenter;
        dateRecieveLabel.backgroundColor = [UIColor clearColor];
        dateRecieveLabel.tag = 555;
        //dateRecieveLabel.text = @"Получено: Fri, 15 Jul 2011";
        [cell addSubview:dateRecieveLabel];
   
  }

  cell.textLabel.text = [[self.newsArray objectAtIndex:indexPath.row]valueForKey:@"NAME"];
  
  NSString *strPubDate = [[self.newsArray objectAtIndex:indexPath.row]valueForKey:@"DATE"];
  NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]autorelease];
  [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
  NSDate *myDate = [dateFormatter dateFromString:strPubDate];
  [dateFormatter setDateFormat:@"EEE, dd LLL yyyy HH:mm"];
  cell.detailTextLabel.text = [dateFormatter stringFromDate:myDate];
  
    
  UILabel * dateRecieveLabelFromCell = (UILabel*)[cell viewWithTag:555];
      int statusOfArticle = [[[self.newsArray objectAtIndex:indexPath.row]valueForKey:@"STATUS"] intValue];
      switch (statusOfArticle) {
        case 0:
          dateRecieveLabelFromCell.text = NSLocalizedString(@"New", @"New");
          break;
        case 1:
          dateRecieveLabelFromCell.text = NSLocalizedString(@"To read later", @"To read later");
          break;
        default:
           dateRecieveLabelFromCell.text = NSLocalizedString(@"Already seen", @"Already seen");
          break;
      } ;
      
  
  UIButton *button = [UIButton buttonWithType:UIButtonTypeInfoDark];
  button.frame = CGRectMake(0, 0, 77, 57);
  [button addTarget:self action:@selector(annotationButtonPressed:) forControlEvents:UIControlEventTouchDown];
  button.titleLabel.font = [UIFont systemFontOfSize:12];
  //[button setTitle:NSLocalizedString(@"annotation", @"annotation") forState:UIControlStateNormal];
  //[button setTitleColor:[UIColor blackColor] forState: UIControlStateNormal];
  //[cell.contentView addSubview:button];
  cell.accessoryView = button;

  return cell;
}

/*- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
  return 75;
}
*/
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
      [self.base articleDidReadWihStatus: [[self.newsArray objectAtIndex:indexPath.row]valueForKey:@"URL"]];
      [self.newsArray removeObjectAtIndex:indexPath.row];
      [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

  [self showDetailViewController:indexPath];
  
}

#pragma mark - Detail Block

- (void)annotationButtonPressed:(id)sender  {
  
  UIButton *button = (UIButton *)sender;
  UITableViewCell *cell = ( UITableViewCell *)[button superview];
  self.indexPathOfCellSelcted = [self.tableView indexPathForCell:cell];
  //NSLog(@"%d", self.indexPathOfCellSelcted);
  
  NSString *title = [[self.newsArray objectAtIndex:self.indexPathOfCellSelcted.row]valueForKey:@"NAME"];
  NSString *message = [[self.newsArray objectAtIndex:self.indexPathOfCellSelcted.row]valueForKey:@"DESC"];
  NSString *link = [[self.newsArray objectAtIndex:self.indexPathOfCellSelcted.row]valueForKey:@"URL"];
  
  UIActionSheet* actionSheet = [[[UIActionSheet alloc] initWithTitle:title
                                                            delegate:self
                                                   cancelButtonTitle:NSLocalizedString(@"Cancel", @"Cancel")
                                              destructiveButtonTitle:nil
                                                   otherButtonTitles:NSLocalizedString(@"Read", @"Read"), nil] autorelease];
  
  UIWebView *webView = [[[UIWebView alloc] initWithFrame:CGRectMake(22.0, 145.0 , 280.0, 245.0)]autorelease];
  webView.opaque = NO;
  [webView setBackgroundColor:[UIColor grayColor]];
  webView.clipsToBounds = YES;
  webView.layer.cornerRadius = 5.0f;
  [webView loadHTMLString:message baseURL:[NSURL URLWithString:link]];  
  [actionSheet addSubview:webView];
  [actionSheet showInView:self.view];
 
  CGRect actionSheetRect = actionSheet.frame;
  CGRect webViewRect = webView.frame;
  
  webViewRect.origin.y = actionSheet.frame.size.height;
  webView.frame = webViewRect;

  actionSheetRect.origin.y -= 270;
  actionSheetRect.size.height = 500;
  actionSheet.frame = actionSheetRect;
  
}

- (void) markArticleAsDidRead: (NSString*) articleURL {

  [self.base articleDidRead: articleURL];
  
 
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
   
  if (buttonIndex == 0) {
      
    [self showDetailViewController:self.indexPathOfCellSelcted];

  }
  
}

- (void) showDetailViewController: (NSIndexPath *)indexPath {
  
  DetailViewController *detail = [[[DetailViewController alloc] init]autorelease];
  NSLog(@"%d", [[[self.newsArray objectAtIndex:indexPath.row]valueForKey:@"STATUS"]intValue]);
  if ([[[self.newsArray objectAtIndex:indexPath.row]valueForKey:@"STATUS"]intValue] == 1 )
  { 
    detail.willReadState = YES;}
  else {
    detail.willReadState = NO;
  }
  detail.link = [[self.newsArray objectAtIndex:indexPath.row]valueForKey:@"URL"];
  [self markArticleAsDidRead: [[self.newsArray objectAtIndex:indexPath.row]valueForKey:@"URL"]];  
  [self.navigationController pushViewController:detail animated:YES];
  
}


- (void) switchNewsView: (UISegmentedControl *) sender {

  NSLog(@"%d", [sender selectedSegmentIndex]);
  self.newsArray = nil;
  [self.tableView reloadData];

}

- (void)refreshRSS:(id)sender {
  
  [[[[DataBase alloc]init]autorelease] updateAllFromInet];
                 
}

- (void) pocessNotification:(NSNotification *) notification { 

  if ( [[notification name] isEqualToString:@"BaseUpdated"] )  {
      self.newsArray = nil;
      [self.tableView reloadData]; 
   }
} 

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
  if ( event.subtype == UIEventSubtypeMotionShake )
  {
    // Put in code here to handle shake
    NSLog(@"-- Shaking recognized --");
    [self refreshRSS:nil];
  }
  if ( [super respondsToSelector:@selector(motionEnded:withEvent:)] )
    [super motionEnded:motion withEvent:event];
}

- (BOOL)canBecomeFirstResponder 
{ 
  return YES; 
}

@end
